package com.example.demo.oo.service;

import com.example.demo.oo.domain.User;

import com.example.demo.oo.domain.UserMoneyLog;
import com.example.demo.oo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserService extends BaseService<User> {

    @Autowired
    UserRepository repository;

    public User loginOrRegister(User user) {

        // 手机号是否注册
        User u = repository.findByMobile(user.getMobile());

        if (u != null) {
            // 重新登陆
            u.reLogin();

            save(u);
            return u;
        }

        // 新用户注册
        user.register();
        save(user);

        return user;
    }

    public void recharge(User user, int money) {

        user = of(user.getId());

        //用户账号增加金额
        user.setMoney(user.getMoney() + money);

        UserMoneyLog log = new UserMoneyLog();
        log.setUserId(user.getId());
        log.setMoney(money);
        user.getMoneyLogs().add(log);

        save(user);
    }


}
